using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Awaiter;
using jQueryApi;

namespace Nsb.Classes
{
    public partial class Evo
    {
        public const string StoreBlobAw = "StoreBlobAw";

        private static readonly Dictionary<string, Evo> EvoEvents = new Dictionary();
        public static readonly Dictionary<string, object> Data = new Dictionary();
        public static bool NoEvoWarnings;

        /// <summary>
        /// Static initializer sets up common Evo triggers
        /// </summary>
        /// <example>Evo.TriggerAw(aw, Evo.StoreBlobAw, new Dictionary())</example>
        static Evo()
        {
            Bind(StoreBlobAw, new Evo().Fn((Action<Await, Dictionary>) FileBlobBase.StoreBlobStringAw));
        }

        public static void Bind(string name, Evo evo)
        {
            EvoEvents[name] = evo;
        }

        [AlternateSignature]
        public static extern void Trigger(string name);

        public static void Trigger(string name, object value)
        {
            try
            {
                if (Arguments.Length > 1)
                    EvoEvents[name].SetValue(value).Fire();
                else
                    EvoEvents[name].Fire();
            }
            catch (Exception ex)
            {
                if (!Type.HasField(EvoEvents, name))
                    Inform.Warn("Evo.Trigger({0}) event unavailable", name);
                else
                    throw ex;
            }
        }

        public static void TriggerAw(Await awp, string name, object value)
        {
            try
            {
                EvoEvents[name].SetValue(value).Fire(awp);
            }
            catch (Exception ex)
            {
                if (!Type.HasField(EvoEvents, name))
                {
                    if (!NoEvoWarnings)
                        Inform.Warn("Evo.TriggerAw({0}) event missing", name);
                }
                else
                    throw ex;
            }
        }

        public static void Set(string name, object value)
        {
            Data[name] = value;
        }

        public static object Get(string name)
        {
            return Data[name];
        }
    }
}